﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;
using System.Data;

using Cisoft.Cisoft3G.Model;
using Cisoft.Cisoft3G.BLL;

public partial class Business_Cisoft3G_InboxManage_VoteEdit : WebUI.Page.BasePage
{
    public static List<TreeNode> tnList = new List<TreeNode>();
    public static string SmsType = string.Empty;

    #region 引用亿美DLL
    [DllImport("EUCPComm.dll", EntryPoint = "SendSMS")]  //即时发送
    public static extern int SendSMS(string sn, string mn, string ct, string priority);

    [DllImport("EUCPComm.dll", EntryPoint = "SendSMSEx")]  //即时发送(扩展)
    public static extern int SendSMSEx(string sn, string mn, string ct, string addi, string priority);

    [DllImport("EUCPComm.dll", EntryPoint = "SendScheSMS")]  // 定时发送
    public static extern int SendScheSMS(string sn, string mn, string ct, string ti, string priority);

    [DllImport("EUCPComm.dll", EntryPoint = "SendScheSMSEx")]  // 定时发送(扩展)
    public static extern int SendScheSMSEx(string sn, string mn, string ct, string ti, string addfi, string priority);
    #endregion

    //亿美产品序列号
    public static string EmeyKey = System.Configuration.ConfigurationManager.AppSettings["EmeyKey"].ToString();
    //亿美产品密码
    public static string EmeyPwd = System.Configuration.ConfigurationManager.AppSettings["EmeyPassword"].ToString();

    #region 页面加载事件
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            for (int i = 0; i < 100; i++)
            {
                tnList.Add(new TreeNode());
            }

            BindTree(0, (TreeNode)null);
            //BindDefineGroup();
            BindTime();
            ltScript.Text = "<script type=\"text/javascript\" src=\"../../../js/My97DatePicker/WdatePicker.js\"></script><script type=\"text/javascript\" src=\"../../../js/MobileJS.js\"></script>";
            txtTime.Attributes.Add("onclick", "WdatePicker({minDate:'%y-%M-{%d}'})");
            //txtTimeNow.Text = DateTime.Now.ToString();

            //获取短信类型
            SmsType = "投票调查";
            if (Session["TP_Mobile"] != null && !string.IsNullOrEmpty(Session["TP_Mobile"].ToString()))
            {
                txtRecive.Text = Session["TP_Mobile"].ToString();
            }
            if (Session["TP_Content"] != null && !string.IsNullOrEmpty(Session["TP_Content"].ToString()))
            {
                string s = Session["TP_Content"].ToString();
                txtSMsContent.Text = s;
                txtSMsContent.Enabled = false;
            }
            Session.Remove("TP_Mobile");
            Session.Remove("TP_Content");
        }
    }
    #endregion

    #region 发送短信
    /// <summary>
    /// 发送短信
    /// </summary>
    protected void btnSend_Click(object sender, EventArgs e)
    {
        int count = new Cisoft.Cisoft3G.BLL.SentBO().GetList(" ST_SentTime >='" + DateTime.Now.ToShortDateString() +
                        " 00:00:00' and ST_SentTime <='" + DateTime.Now.ToShortDateString() + " 23:59:59' ").Tables[0].Rows.Count +
                        new Cisoft.Cisoft3G.BLL.OutboxBO().GetList(" OB_SendTime >='" + DateTime.Now.ToShortDateString() +
                        " 00:00:00' and OB_SendTime <='" + DateTime.Now.ToShortDateString() + " 23:59:59' ").Tables[0].Rows.Count;
        if (count > 5)
        {
            string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=False&Message=" + "短信发送失败！失败原因如下： " + "本日短信配额已用完" + "。" + "&Url=AddSms.aspx'") + ")";
            PageError(ModalPopupExtender1, lblTS, btnBack_ts, "短信发送失败！失败原因如下：本日短信配额已用完");
        }
        else
        {
            //判断要发送的短信和已经发送的短信条数和是否大于5条
            if (txtRecive.Text.Trim().TrimEnd(',').Split(',').Length + count > 5)
            {
                PageError(ModalPopupExtender1, lblTS, btnBack_ts, "短信发送失败！失败原因如下： " +
                    "您今天已经发送" + count + "条短信。您要发送的短信条数过多，请核对本日短信配额后重试。");
            }

            //立即发送
            if (rbtnNow.Checked)
            {
                SendNowSms();
            }
            //定时发送
            if (rbtnTime.Checked)
            {
                SendTimeSMS();
            }
        }
    }
    #endregion

    #region 自定义方法立即发送短信
    private void SendNowSms()
    {
        string strSysError = string.Empty;
        string strEmeyError = string.Empty;

        Cisoft.Cisoft3G.BLL.SentBO bll = new Cisoft.Cisoft3G.BLL.SentBO();
        Cisoft.Cisoft3G.Model.SentMO model = new Cisoft.Cisoft3G.Model.SentMO();

        string[] mobiles = txtRecive.Text.Trim().TrimEnd(',').Split(',');

        try
        {
            foreach (string s in mobiles)
            {
                strEmeyError = EmeySmsSend(s, txtSMsContent.Text.Trim());
                if (strEmeyError == "发送成功")
                {
                    model.ST_SentID = bll.GetMaxId();
                    model.ST_Recive = s;
                    model.ST_SentTime = DateTime.Now;
                    model.ST_SmsContent = txtSMsContent.Text.Trim();
                    model.ST_SmsID = System.Guid.NewGuid().ToString();
                    model.ST_SmsType = string.IsNullOrEmpty(SmsType) ? "普通" : SmsType;
                    bll.Add(model);
                }
            }
        }
        catch (Exception ex)
        {

        }
        if (strEmeyError == "发送成功")
        {
            if (!string.IsNullOrEmpty(strSysError))
            {
                PageError(ModalPopupExtender1, lblTS, btnBack_ts, "短信发送失败！失败原因如下： " + strSysError);
            }
            else
            {
                PageRight(ModalPopupExtender1, lblTS, btnBack_ts, "<h4>短信发送成功！</h4>", "../SentboxManage/SentboxManage.aspx");
            }
        }
        else
        {
            PageError(ModalPopupExtender1, lblTS, btnBack_ts, "短信发送失败！失败原因如下： " + strSysError);
        }
    }
    #endregion

    #region 自定义方法定时发送短信
    private void SendTimeSMS()
    {
        string strError = string.Empty;

        DateTime time = Convert.ToDateTime(txtTime.Text.Trim() + " " + selectHour.Value + ":" + selectMinite.Value);

        if (time <= DateTime.Now)
        {
            PageError("定时发送时间必须大于当前时间！", Request.RawUrl);
        }

        Cisoft.Cisoft3G.BLL.OutboxBO bll = new Cisoft.Cisoft3G.BLL.OutboxBO();
        Cisoft.Cisoft3G.Model.OutboxMO model = new Cisoft.Cisoft3G.Model.OutboxMO();

        string[] mobiles = txtRecive.Text.Trim().TrimEnd(',').Split(',');

        try
        {
            foreach (string s in mobiles)
            {
                model.OB_OutBoxiD = bll.GetMaxId();
                model.OB_Recive = s;
                model.OB_SendTime = time;
                model.OB_SMContent = txtSMsContent.Text.Trim();
                model.OB_SmsID = System.Guid.NewGuid().ToString();
                //model.RT_Type_FK = 1;
                model.RT_Type_FK = Convert.ToInt32(new Cisoft.Cisoft3G.BLL.SmsTypeBO().GetIDByName(SmsType));
                bll.Add(model);
            }
        }
        catch (Exception ex)
        {
            strError = ex.Message;
        }

        if (!string.IsNullOrEmpty(strError))
        {
            PageError(ModalPopupExtender1, lblTS, btnBack_ts, "短信发送失败！失败原因如下： " + strError);
        }
        else
        {
            PageRight(ModalPopupExtender1, lblTS, btnBack_ts, "<h4>短信发送成功！</h4>");
        }
    }
    #endregion

    #region 亿美短信发送方法
    private string EmeySmsSend(string mobile, string content)
    {
        int result = SendSMS(EmeyKey, mobile, content, "5");
        if (result == 1)
            return "发送成功";
        else if (result == 101)
            return "网络故障";
        else if (result == 102)
            return "其它故障";
        else if (result == 0)
            return "失败";
        else if (result == 100)
            return "序列号码为空或无效";
        else if (result == 107)
            return "手机号码为空或者超过1000个";
        else if (result == 108)
            return "手机号码分割符号不正确";
        else if (result == 109)
            return "部分手机号码不正确，已删除，其余手机号码被发送";
        else if (result == 110)
            return "短信内容为空或超长（70个汉字）";
        else if (result == 201)
            return "计费失败，请充值";
        else
            return "其他故障值：" + result.ToString();
    }
    #endregion

    #region 绑定时间 void BindTime()
    private void BindTime()
    {
        for (int i = 0; i < 23; i++)
        {
            ListItem item = new ListItem(i.ToString("00"), i.ToString("00"));
            selectHour.Items.Add(item);
        }
        for (int i = 0; i < 59; i++)
        {
            ListItem item = new ListItem(i.ToString("00"), i.ToString("00"));
            selectMinite.Items.Add(item);
        }
    }
    #endregion

    #region 呼叫通讯录
    protected void btnCallContacts_Click(object sender, EventArgs e)
    {
        LinkButton1_Click(sender, e);
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        ModalPopupExtender3.Show();
    }
    #endregion

    #region 通讯录 确定添加联系人
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtRecive.Text))
        {
            txtRecive.Text = hih_right.Value;
        }
        else
        {
            txtRecive.Text = txtRecive.Text.TrimEnd(',') + "," + hih_right.Value;
        }
        ModalPopupExtender3.Hide();
    }
    #endregion

    #region 处理通讯录字符串
    private string GetFilterString(string input)
    {
        List<string> strList = new List<string>();
        string strFilter = string.Empty;

        string[] strs = input.TrimEnd(',').Split(',');
        foreach (string s in strs)
        {
            try
            {
                Int64 d = Convert.ToInt64(s.Substring(s.Length - 11, 11));
                //检查是否有重复字符串
                if (!txtRecive.Text.Contains(d.ToString()))
                {
                    strList.Add(d.ToString());
                }
            }
            catch (Exception ex)
            {
                continue;
            }
        }
        if (strList.Count > 0)
        {
            strFilter = string.Join(",", strList.ToArray());
        }

        return strFilter;
    }
    #endregion

    #region 绑定TreeView数据
    //绑定TreeView数据
    private void BindTree(int pid, TreeNode node)
    {
        List<ContactGroupMO> modelList = new ContactGroupBO().GetModelList(" CG_ParentID = " + pid + " order by CG_Order desc");
        foreach (ContactGroupMO model in modelList)
        {
            TreeNode tn = new TreeNode();
            if (node == null)
            {
                tn = new TreeNode();
                tn.Text = "<a style='text-decoration:none;' href='GetContactsHandler.ashx?ContactGroupID=" + model.CG_ContactGroupID + "'>" + model.CG_GroupName + "</a>";
                tn.NavigateUrl = "javascript:void(0);";
                tvContactsGroup.Nodes.Add(tn);
                BindTree(model.CG_ContactGroupID, tn);
            }
            else
            {
                tn = new TreeNode();
                tn.Text = "<a style='text-decoration:none;' href='GetContactsHandler.ashx?ContactGroupID=" + model.CG_ContactGroupID + "'>" + model.CG_GroupName + "</a>";
                tn.NavigateUrl = "javascript:void(0);";
                node.ChildNodes.Add(tn);
                BindTree(model.CG_ContactGroupID, tn);
            }
        }
    }

    private void BindTree()
    {
        List<ContactGroupMO> modelList = new ContactGroupBO().GetModelList(" order by CG_ParentID");
        foreach (ContactGroupMO model in modelList)
        {
            int fid = Convert.ToInt32(model.CG_ParentID);
            int id = model.CG_ContactGroupID;

            tnList[id].Text = model.CG_GroupName;
            tnList[id].NavigateUrl = "GetContactsHandler.ashx?ContactGroupID=" + id;
            if (fid != 0)
            {
                tnList[fid].ChildNodes.Add(tnList[id]);
            }
            else
            {
                tvContactsGroup.Nodes.Add(tnList[id]);
            }
        }
    }
    //绑定自定义组
    private void BindDefineGroup()
    {
        List<DefineGroupMO> list = new DefineGroupBO().GetModelList("");
        foreach (DefineGroupMO model in list)
        {
            lblDefineGroup.Text += string.Format("<tr><td valign='top'><a style='text-decoration:none;' href='{0}'>{1}</a></td></tr>", "GetContactsHandler.ashx?DefineGroupID=" + model.DG_ID, model.DG_Name);
        }
    }
    #endregion

    #region 获取短信类型
    private string GetSMSType()
    {
        string strType = string.Empty;
        if (Request.QueryString["SmsType"] != null && Request.QueryString["SmsType"].ToString() != "")
        {
            strType = Server.HtmlDecode(Request.QueryString["SmsType"].ToString());
        }
        return strType;
    }
    #endregion
}
